import { defineComponent, onMounted, onUnmounted, ref, KeepAlive } from "vue";
import styles from "./index.module.less";
import Header from "@/components/Header/Header";
import Footer from "@/components/Footer/Footer";
import router from "@/router";
import LoginPopup from "@/components/LoginPopup/LoginPopup";
import { imgPath } from "@/common/utils";
import { useStore as useUserStore } from "@/store/user";
import { $loginUser } from "@/api/login/login";
import eventBus from "@/common/mitt";
import { useStore as useCacheViewStore } from "@/store/cacheView";
export default defineComponent({
  name: 'index',
  setup() {
    const cacheViewStore = useCacheViewStore();
    const userStore = useUserStore();

    // 主体部分
    const Main = () => (
      <div class={styles.main}>
        <router-view>
          {
            ({ Component, route }: { Component: any, route: any }) => {
              return (
                <KeepAlive include={cacheViewStore.cacheView}>
                  <Component key={route.name} />
                </KeepAlive>
              )
            }
          }
        </router-view>
      </div>
    )
    // 跳转客服聊天
    const toContactChat = () => {

    }
    // 客服悬浮标
    const Contact = () => (
      <img class={styles['contact-float']} src={imgPath('/contact-float.png')} onClick={() => toContactChat()} />
    )

    // 执行登录
    const toLogin = () => {
      LoginPopupRef.value.open();
    }

    const LoginPopupRef = ref(null as any);


    // 获取用户信息
    const getUserInfo = () => {
      $loginUser().then((res: any) => {
        userStore.setUserInfo(res?.data?.user || {});
      })
    }


    onMounted(() => {
      eventBus.payed.on(() => {
        getUserInfo();
      });
    })

    onUnmounted(() => {
      eventBus.payed.off();
    })

    return () => (
      <div class={styles.index}>
        <Header onToLogin={() => { toLogin() }} onToRegister={() => { router.push('/register') }} />
        <Main />
        <Footer />
        {/* <Contact /> */}
        <LoginPopup ref={LoginPopupRef} />
      </div>
    )
  }
})